package cn.itcast.demo;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

// 此类用于将数据生成到kafka中
public class KafkaProducerTest {

    public static void main(String[] args) {

        //1. 创建kafka生成者核心类对象:   KafkaProducer

        //1.1: 设置相关的配置信息
        Properties props = new Properties();
        props.put("bootstrap.servers", "node1:9092");
        props.put("acks", "all"); // ack确认机制, 用于保证生产者在发送数据的不丢失
        // 设置 key 和 vlaue 发送数据的序列化类
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        Producer<String, String> producer = new KafkaProducer<>(props);

        //2. 发送数据
        for (int i = 0; i < 5; i++) {
            //2.1: 发送端 用于承载数据的对象
            ProducerRecord<String, String> producerRecord = new ProducerRecord<>("test3", i+"" ,Integer.toString(i));

            //2.2: 执行发送
            producer.send(producerRecord);
        }
        //3. 释放资源
        producer.close();
    }

}
